// utils.h
#ifndef UTILS_H
#define UTILS_H

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>

static inline unsigned char *read_file(const char *filename, size_t *len) {
    FILE *fp = fopen(filename, "rb");
    if (!fp) {
        perror("fopen");
        exit(1);
    }
    struct stat st;
    if (fstat(fileno(fp), &st) != 0) {
        perror("fstat");
        fclose(fp);
        exit(1);
    }
    *len = st.st_size;
    unsigned char *buf = malloc(*len);
    if (!buf) {
        perror("malloc");
        fclose(fp);
        exit(1);
    }
    if (fread(buf, 1, *len, fp) != *len) {
        perror("fread");
        free(buf);
        fclose(fp);
        exit(1);
    }
    fclose(fp);
    return buf;
}

static inline void write_file(const char *filename, const unsigned char *data, size_t len) {
    FILE *fp = fopen(filename, "wb");
    if (!fp) {
        perror("fopen");
        exit(1);
    }
    if (fwrite(data, 1, len, fp) != len) {
        perror("fwrite");
        fclose(fp);
        exit(1);
    }
    fclose(fp);
}

#endif
